﻿#include "wifi.h"
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <QGridLayout>
#include <QString>
#include <QTimer>
#include <QList>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <qdebug.h>
#include <qfile.h>
#include <QFile>
#include <sys/ioctl.h>
#include <unistd.h>
#include <QString>
#include <QNetworkInterface>
#include <QList>
#include <QFrame>
#include "InputMethod/inputmethod.h"
#include <QStringList>
// version 1

extern "C" {
#include "dirent.h"
#include <cstdio>
#include <unistd.h>
#include "wpa_ctrl.h"
}

extern long long get_file_size(const char *path);

extern bool	GetIPV4Gateway(const char *, char *, unsigned long);  




struct wpa_ctrl *ctrl_conn;
struct wpa_ctrl *monitor_conn;
char *ctrl_iface_dir;
char *ctrl_iface;
QString nowZItemWifiName;
QString nowZItemWifiKey;
QString flagstmp="无密码";
QString ssid, bssid, freq, signal, flags;
int minimum = -95;
int maximum = -35;
int linkflag =0;
int havewlanflag=1;
int nowhavewifi=0;
QLineEdit   *DipWifi;

Wifilian::Wifilian(QWidget *parent) : QDialog(parent){

        wifilianflag=1;
        flagcount=0;
        giflabel = new QLabel(this);
        giflabelt = new QLabel(this);
        giflabelt->setText(tr("正在连接"));
        giflabel->setContentsMargins(0,0,0,0);
        QMovie *movie = new QMovie(":/images/wai.gif");
        giflabel->setMovie(movie);
        movie->start();
        QTimer*timer66 = new QTimer(this);
        timer66->start(1000);
        connect(timer66,SIGNAL(timeout()),this,SLOT(wifitime()));

        QGridLayout *tmplayoutl = new QGridLayout;
        tmplayoutl->addWidget(giflabelt,0,0,1,1);
        tmplayoutl->addWidget(giflabel,0,1,1,1);
        this->setLayout(tmplayoutl);
        this->setWindowFlags(Qt::FramelessWindowHint);
        this->exec();
}

void Wifilian::wifitime()
{
    if(wifilianflag){
        QFile::remove("/tmp/islinkok.c");
        system("ifconfig wlan0 > /tmp/islinkok.c");
        QFile filetmplink("/tmp/islinkok.c");
        filetmplink.open(QFile::ReadOnly);
        QString stmp =filetmplink.readAll();
        QString stmp2="Mask:";
        QString stmp3="Bcast:";
        if(stmp.contains(stmp2) && stmp.contains(stmp3)) {
            wifilianflag=0;

/**/
            int began=0;
            int ON =1;
            system("ifconfig wlan0 | grep \"inet addr:\" > /tmp/wifiipli.c");//inet addr:192.168.23.2  Bcast:192.168.23.255  Mask:255.255.255.0
            QFile filewifi("/tmp/wifiipli.c");
            filewifi.open(QIODevice::ReadWrite);
            QString str(filewifi.readAll());
            QString tmp;
            for(int i = 0;i<str.length();i++)
            {
                if(str[i]==':'){
                    i++;
                    began=1;
                }
                if(began)
                if(str[i]!=' '&& (ON) && str[i]!='B')
                   tmp.append(str[i]);
                if(str[i]=='B')
                    ON=0;
            }
             DipWifi->setText(tmp);
             filewifi.close();
/**/
            QDialog * setdialog = new QDialog;
            QLabel * settmp = new QLabel;
            settmp->setText(tr("连接成功"));
            settmp->setStyleSheet("color:green;");
            QTimer*timer = new QTimer(setdialog);
            timer->start(600);
            connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
            QGridLayout *tmplayout = new QGridLayout;
            tmplayout->addWidget(settmp,0,0,1,1);
            setdialog->setLayout(tmplayout);
            setdialog->setWindowFlags(Qt::FramelessWindowHint);
            setdialog->exec();
            wifilianflag=0;

			

            if(!nowhavewifi){// ru guo mei you ze bao cun zhui xing SAVE_CONFIG
            char reply[2048];
            size_t reply_len = sizeof(reply);

            char *cmd2;
            QString command_full2;
            command_full2.append("SAVE_CONFIG");
            cmd2 = (command_full2.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);
            system("sync");
            qDebug("start inv");

                if ((strstr(reply, "FAIL")!=NULL) || (strstr(reply, "fail")!=NULL) || (strstr(reply, "Fail")!=NULL))
                   qDebug("Failed to save configuration");

            else
                    qDebug("Saved configuration");
            }else {// ru guo you le ze bu bao cun
                ;
            }
        }
        flagcount++;
        if(flagcount>35){
            QDialog * setdialog = new QDialog;
            QLabel * settmp = new QLabel;
            settmp->setText(tr("连接失败.密码是否正确"));
            settmp->setStyleSheet("color:red;");
            QTimer*timer = new QTimer(setdialog);
            timer->start(600);
            connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
            QGridLayout *tmplayout = new QGridLayout;
            tmplayout->addWidget(settmp,0,0,1,1);
            setdialog->setLayout(tmplayout);
            setdialog->setWindowFlags(Qt::FramelessWindowHint);
            setdialog->exec();
            wifilianflag=0;
            sleep(1);
        }
    }

    if(!wifilianflag){
        this->close();
    }
}

Wifilian::~Wifilian() {

}

Wifipassword::Wifipassword(QWidget *parent) : QDialog(parent){

   im2 = new InputMethod;
   qlineedit_password = new QLineEdit;
   qlinkButton        = new QPushButton;
   qcloseButton       = new QPushButton;
   qlinkLabel         = new QLabel;
   qsignallevelLabel  = new QLabel;
   qsignallevelQSlider= new QSlider(Qt::Horizontal);
   qlinkButton->setText(tr("连接"));
   qcloseButton->setText(tr("关闭"));
   qlinkLabel->setText(tr("密码："));
   qsignallevelLabel->setText(tr("信号强度:"));
   qlinkButton->setMinimumSize(30,50);
   qcloseButton->setMinimumSize(30,50);
   qlineedit_password->setMinimumSize(30,50);
   qsignallevelQSlider->setRange(-95,-35);
   qsignallevelQSlider->setValue(-95);
   qsignallevelQSlider->setEnabled(false);
   qsignallevelQSlider->setStyleSheet("  \
         QSlider::add-page:Horizontal\
         {     \
            background-color: rgb(87, 97, 106);\
            height:4px;\
         }\
         QSlider::sub-page:Horizontal \
        {\
            background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(231,80,229, 255), stop:1 rgba(7,208,255, 255));\
            height:4px;\
         }\
        QSlider::groove:Horizontal \
        {\
            background:transparent;\
            height:6px;\
        }\
        QSlider::handle:Horizontal \
        {\
            height: 30px;\
            width:8px;\
            border-image: url(:/images/ic_music_thumb.png);\
            margin: -8 0px; \
        }\
        ");

   connect(qcloseButton,SIGNAL(clicked()),this,SLOT(close()));
   connect(qlinkButton,SIGNAL(clicked(bool)),this,SLOT(linkButtonWifiFun()));
   qlineedit_password->installEventFilter(im2);
   qlineedit_password->setObjectName("qlineedit_password");
    QString tmp="无密码";
   if(nowZItemWifiName.contains(tmp)){
       qlineedit_password->setText(tr("无密码"));
       qlineedit_password->setEnabled(false);
     }else{
       connect(im2,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect2(QString)));//connect the input method

   }

    QGridLayout *pPassWordLayout = new QGridLayout;
    pPassWordLayout->addWidget(qlinkLabel, 0, 0, 1, 1);
    pPassWordLayout->addWidget(qlineedit_password, 0, 1, 1, 1);
    pPassWordLayout->addWidget(qcloseButton, 2, 0, 1, 1);
    pPassWordLayout->addWidget(qlinkButton, 2, 1, 1, 1);

    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setLayout(pPassWordLayout);
}

void Wifipassword::createImConnect2(QString ObjName)
{
    disconnect(im2->keyboard,SIGNAL(setvalue(QString)),qlineedit_password,SLOT(setText(QString)));
    if(ObjName=="qlineedit_password")
        connect(im2->keyboard,SIGNAL(setvalue(QString)),qlineedit_password,SLOT(setText(QString)));
}

int Wifipassword::ctrlRequest(const char *cmd, char *buf, size_t *buflen)
{
    int ret;
    if(cmd!="PING")
    if (ctrl_conn == NULL)
        return -3;
    ret = wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), buf, buflen, NULL);
    if (ret == -2)
        printf("'%s' command timed out.\n", cmd);
    else if (ret < 0)
        printf("'%s' command failed.\n", cmd);

    return ret;
}

void Wifipassword::selectNetwork()
{
    QString cmd;
    char reply[10];
    size_t reply_len = sizeof(reply);

    if (cmd.contains(QRegExp("^\\d+:")))
        cmd.truncate(cmd.indexOf(':'));
    else
        cmd = "any";
    cmd.prepend("SELECT_NETWORK ");
    char * cmdtmp="SELECT_NETWORK 1";
    ctrlRequest(cmdtmp, reply, &reply_len);
}

void Wifipassword::saveConfig()
{
    char buf[10];
    size_t len;

    len = sizeof(buf) - 1;
    ctrlRequest("SAVE_CONFIG", buf, &len);

    buf[len] = '\0';

//    if (str_match(buf, "FAIL"))
     if (strstr(buf, "FAIL")!=NULL)
         qDebug("Failed to save configuration");
     /*   QMessageBox::warning(
            this, tr("Failed to save configuration"),
            tr("The configuration could not be saved.\n"
               "\n"
               "The update_config=1 configuration option\n"
               "must be used for configuration saving to\n"
               "be permitted.\n"));*/
    else
         qDebug("Saved configuration");
       /* QMessageBox::information(
            this, tr("Saved configuration"),
            tr("The current configuration was saved."
               "\n")); */
}

char * Wifipassword::connectB()
{
    char reply[10];
    size_t reply_len = sizeof(reply);
    char *cmd="REASSOCIATE";
    wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), reply, &reply_len, NULL);
    return reply;
}

char * Wifipassword::disconnectwifi()
{
    char reply[10];
    size_t reply_len = sizeof(reply);
    char *cmd="DISCONNECT";
    wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), reply, &reply_len, NULL);
    return reply;
}

void Wifipassword::linkButtonWifiFun()
{
    QString tmp="无密码";
    int flag=1;
   if(nowZItemWifiName.contains(tmp)){
       flag=1;
     }else
       if((qlineedit_password->text().length()<8)) {
       QDialog * setdialog = new QDialog;
       QLabel * settmp = new QLabel;
       if((qlineedit_password->text().length()<8))
       settmp->setText(tr("密码长度必须大于等于8位!"));
       settmp->setStyleSheet("color:red;");
       QTimer*timer = new QTimer(setdialog);
       timer->start(600);
       connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
       QGridLayout *tmplayout = new QGridLayout;
       tmplayout->addWidget(settmp,0,0,1,1);
       setdialog->setLayout(tmplayout);
       setdialog->setWindowFlags(Qt::FramelessWindowHint);
       setdialog->exec();
       flag=0;
   }  //else
   if(flag)
   {

    QString stmp2;

    system("killall -9 udhcpc");

    int i =0;
    while(nowZItemWifiName[i]!='\n')
    {
        stmp2.append(nowZItemWifiName[i++]);
    }

    QString keynull="无密码";
    QString keywpa="WPA";
    QString keywep="WEP";

    char reply[2048];
    char replytmp [2];
    size_t reply_len = sizeof(reply);
    size_t reply_lentmp = sizeof(replytmp);
    char *cmd;
    char *cmd1;
    char *cmd2;
    char *cmd3;
    char *cmd4;
    char *cmd5;
    char *cmd6;
    char *cmd7;
    QString command_full1;
    QString command_full2;
    QString command_full3;
    QString command_full4;
    QString command_full5;
    QString command_full6;
    QString command_full7;

    if(nowZItemWifiName.contains(keynull))
    {
        cmd="ADD_NETWORK";
        wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), replytmp, &reply_lentmp, NULL);

        cmd5="DISABLE_NETWORK all";
        wpa_ctrl_request(ctrl_conn, cmd5, strlen(cmd5), reply, &reply_len, NULL);


        command_full1.append("SET_NETWORK ");
        command_full1.append(replytmp[0]);
        command_full1.append(" ssid ");
        command_full1.append("\"");
        command_full1.append(stmp2);
        command_full1.append("\"");
        cmd1 = (command_full1.toAscii()).data();
        wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);


      //  cmd="SET_NETWORK 6 PSK \"crl6crl6crl6\"";
        command_full2.append("SET_NETWORK ");
        command_full2.append(replytmp[0]);
        command_full2.append(" key_mgmt NONE");
     //   command_full2.append(qlineedit_password->text().toAscii().data());
        cmd2 = (command_full2.toAscii()).data();
        wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);

     //   cmd="SELECT_NETWORK 6";
        command_full3.append("SELECT_NETWORK ");
        command_full3.append(replytmp[0]);
        cmd3 = (command_full3.toAscii()).data();
        //"select_network cmd= %s",cmd3);
        wpa_ctrl_request(ctrl_conn, cmd3, strlen(cmd3), reply, &reply_len, NULL);

     //   cmd="ENABLE_NETWORK 6";
        command_full4.append("ENABLE_NETWORK ");
        command_full4.append(replytmp[0]);
        cmd4 = (command_full4.toAscii()).data();
        wpa_ctrl_request(ctrl_conn, cmd4, strlen(cmd4), reply, &reply_len, NULL);

    }else{
    if(nowZItemWifiName.contains(keywpa)){
        cmd="ADD_NETWORK";
        wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), replytmp, &reply_lentmp, NULL);

        command_full5.append("DISABLE_NETWORK ");
        command_full5.append((replytmp[0]-1));
        cmd5 = (command_full5.toAscii()).data();
        cmd5="DISABLE_NETWORK all";
        wpa_ctrl_request(ctrl_conn, cmd5, strlen(cmd5), reply, &reply_len, NULL);


        command_full1.append("SET_NETWORK ");
        command_full1.append(replytmp[0]);
        command_full1.append(" ssid ");
       // command_full1.append("\"123456789bbb\"");
        command_full1.append("\"");
        command_full1.append(stmp2);
        command_full1.append("\"");
       // cmd="SET_NETWORK 4 ssid \"crl67crl678\"";
        cmd1 = (command_full1.toAscii()).data();
        //"set_network ssid cmd= %s",cmd1);
        wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);
        //"set_network 0 ssid= %s",reply);

      //  cmd="SET_NETWORK 6 PSK \"crl6crl6crl6\"";
        command_full2.append("SET_NETWORK ");
        command_full2.append(replytmp[0]);
        command_full2.append(" psk ");
        command_full2.append("\"");
      //  command_full2.append("\"crl6crl6crl6\"");
        command_full2.append(qlineedit_password->text().toAscii().data());
        command_full2.append("\"");
     //   command_full2.append(qlineedit_password->text().toAscii().data());
        cmd2 = (command_full2.toAscii()).data();
        //"set_network psk cmd= %s",cmd2);
        wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);
        //"set_network 0 psk= %s",reply);

     //   cmd="SELECT_NETWORK 6";
        command_full3.append("SELECT_NETWORK ");
        command_full3.append(replytmp[0]);
        cmd3 = (command_full3.toAscii()).data();
        wpa_ctrl_request(ctrl_conn, cmd3, strlen(cmd3), reply, &reply_len, NULL);

        command_full4.append("ENABLE_NETWORK ");
        command_full4.append(replytmp[0]);
        cmd4 = (command_full4.toAscii()).data();
        wpa_ctrl_request(ctrl_conn, cmd4, strlen(cmd4), reply, &reply_len, NULL);
    }else{
        //wep
        if(nowZItemWifiName.contains(keywep))
            {
            cmd="ADD_NETWORK";
            wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), replytmp, &reply_lentmp, NULL);

            command_full5.append("DISABLE_NETWORK ");
            command_full5.append((replytmp[0]-1));
            cmd5 = (command_full5.toAscii()).data();
            cmd5="DISABLE_NETWORK all";
            wpa_ctrl_request(ctrl_conn, cmd5, strlen(cmd5), reply, &reply_len, NULL);

            command_full1.append("SET_NETWORK ");
            command_full1.append(replytmp[0]);
            command_full1.append(" ssid ");
            command_full1.append("\"");
            command_full1.append(stmp2);
            command_full1.append("\"");
            cmd1 = (command_full1.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);

            command_full6.append("SET_NETWORK ");
            command_full6.append(replytmp[0]);
            command_full6.append(" key_mgmt NONE");
            cmd6 = (command_full6.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd6, strlen(cmd6), reply, &reply_len, NULL);

            command_full7.append("SET_NETWORK ");
            command_full7.append(replytmp[0]);
            command_full7.append(" wep_key0 ");
            command_full7.append("\"");
            command_full7.append(qlineedit_password->text().toAscii().data());
            command_full7.append("\"");
            cmd7 = (command_full7.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd7, strlen(cmd7), reply, &reply_len, NULL);

            command_full2.append("SET_NETWORK ");
            command_full2.append(replytmp[0]);
            command_full2.append(" wep_tx_keyidx 0");
            cmd2 = (command_full2.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);

            command_full3.append("SELECT_NETWORK ");
            command_full3.append(replytmp[0]);
            cmd3 = (command_full3.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd3, strlen(cmd3), reply, &reply_len, NULL);
            command_full4.append("ENABLE_NETWORK ");
            command_full4.append(replytmp[0]);
            cmd4 = (command_full4.toAscii()).data();
            wpa_ctrl_request(ctrl_conn, cmd4, strlen(cmd4), reply, &reply_len, NULL);
            }
    }
    }

    system("killall -9 udhcpc");
    QFile filetmptt("/etc/init.d/wifi_sh");
    filetmptt.open(QFile::WriteOnly);
    QTextStream stmptt(&filetmptt);
    stmptt<<"#!/bin/sh"<<"\n";
    stmptt<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R "<<"\n";;
    filetmptt.close();
    system("sync");
    system("chmod +x /etc/init.d/wifi_sh");
    QProcess *proc =new QProcess;
    proc->start("/etc/init.d/wifi_sh");// fei zu sai
    usleep(10000);
    filetmptt.open(QFile::WriteOnly);
    QTextStream stmptt2(&filetmptt);
    stmptt2<<"#!/bin/sh"<<"\n";
    stmptt2<<"wpa_supplicant -B -d -i wlan0 -c /etc/wifi/wpa_supplicant.conf "<<"\n";;
    stmptt2<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R "<<"\n";
    filetmptt.close();
    system("sync");
  //  int flag =1;
   // int flagcount =0;

      Wifilian wifiliantmp;
      wifiliantmp.exec();

  
    this->close();
   }
}

Wifipassword::~Wifipassword()
{
}

void WifiSeting::refreshLabelPos()
{
    QFile::remove("/tmp/zhuangtai.c");
    system("ifconfig wlan0 > /tmp/zhuangtai.c");
    
    QFile filetmplink("/tmp/zhuangtai.c");
    filetmplink.open(QFile::ReadOnly);
    QString stmp =filetmplink.readAll();
    QString stmp2="Mask:";
    QString stmp3="Bcast:";
	QString stmp4="off/any";
	QString tmp0;
	
     QFile::remove("/tmp/zhuangtai1");
     system("iwconfig wlan0 | grep ESSID:  >>/tmp/zhuangtai1");
     
     QFile filetmplink6("/tmp/zhuangtai1");
     filetmplink6.open(QFile::ReadOnly);
     tmp0 =filetmplink6.readAll();
     QString tmp;
     
     if(stmp.contains(stmp2) && stmp.contains(stmp3) && (!tmp0.contains(stmp4))) {
		int colon_cnt = 0;
        QString tmp1;
        tmp="已连接:";
        int began=0;
        for(int i=0; i<tmp0.length(); i++){
            if(tmp0[i]=='E' && tmp0[i+1]=='S' && tmp0[i+2]=='S' && tmp0[i+3]=='I') {
                i=i+6;
                began=1;
            }
            if(began)
                if(tmp0[i] != '"')
                {
                	tmp1.append(tmp0[i]);
                }
				else
				{
					colon_cnt++;
					if(2 == colon_cnt)
					{
						tmp1.append('\0');
						break;
					}
				}
        }
        tmp.append(tmp1);
        linkStat->setStyleSheet("color:green;background-color:rgb(80,120,89,80);");

    }else{
        tmp="无连接";
        linkStat->setStyleSheet("color:red;background-color:rgb(80,120,89,80);");

    }
   linkStat->setText(tmp);
}


void WifiSeting::forgetPasswd()
{
	qDebug("forget passwd");

	if(get_file_size("/etc/wifi/wpa_supplicant.conf.backup") <= 0)
	{
		QMessageBox::information(NULL, tr("错误"), tr("配置文件不存在,清空密码失败!"));	
		return ;
	}

	system("rm /etc/wifi/wpa_supplicant.conf &");

	while(get_file_size("/etc/wifi/wpa_supplicant.conf") != -1)
		qDebug("/etc/wifi/wpa_supplicant.conf is not remove");

	system("cp /etc/wifi/wpa_supplicant.conf.backup /etc/wifi/wpa_supplicant.conf &");
	system("sync &");

	while(get_file_size("/etc/wifi/wpa_supplicant.conf") <= 0)
		qDebug("/etc/wifi/wpa_supplicant.conf is create");

	QMessageBox::information(NULL, tr("成功"), tr("忘记所有WIFI密码成功"));	
}


WifiSeting::WifiSeting(QWidget *parent) : JDialog(parent)
{ 
   system("cat /etc/resolv2.conf > /etc/resolv.conf ");
   system("ifconfig -a | grep wlan >/tmp/HAVEwlan.dat");
   QFile filetmpwlan("/tmp/HAVEwlan.dat");
   filetmpwlan.open(QFile::ReadOnly);
   QString stmpwlan =filetmpwlan.readAll();
   QString stmp2wlan="wlan";
   nowhavewifi=0;
   havewlanflag=1;
   QFile filetmpwlan2("/etc/wifi/wpa_supplicant.conf");

   if( !filetmpwlan2.exists()) {
       QDialog * setdialog = new QDialog;
       QLabel * settmp = new QLabel;
       settmp->setText(tr("请检查WIFI配置文件"));
       settmp->setStyleSheet("color:red;");
       QTimer*timer = new QTimer(setdialog);
       timer->start(1000);
       connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
       QGridLayout *tmplayout = new QGridLayout;
       tmplayout->addWidget(settmp,0,0,1,1);
       setdialog->setLayout(tmplayout);
       setdialog->setWindowFlags(Qt::FramelessWindowHint);
       setdialog->exec();
       this->setJTitle(tr("WIFI设置"));
   }
   else
   if(!stmpwlan.contains(stmp2wlan) ){
       havewlanflag=0;
       QDialog * setdialog = new QDialog;
       QLabel * settmp = new QLabel;
       settmp->setText(tr("标配版没有WIFI模块"));
       settmp->setStyleSheet("color:red;");
       QTimer*timer = new QTimer(setdialog);
       timer->start(1000);
       connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
       QGridLayout *tmplayout = new QGridLayout;
       tmplayout->addWidget(settmp,0,0,1,1);
       setdialog->setLayout(tmplayout);
       setdialog->setWindowFlags(Qt::FramelessWindowHint);
       setdialog->exec();
       //this->setJTitle(tr("WIFI设置"));
       QFrame *pFrame = new QFrame;
       QGridLayout *pMainLayout = new QGridLayout;
       pMainLayout->addWidget(pFrame, 0, 0, 1, 1);
       pMainLayout->setContentsMargins(40, 15, 40, 15);
       pFrame->setObjectName("wifiSettingsFrame");
       this->setJLayout(pMainLayout);
       this->setJTitle(tr("WIFI设置"));

   }else {
    wificount=0;
    system("ps |pgrep -l wpa_supplicant >/tmp/HAVEWPA.dat");
    QFile filetmpwifi("/tmp/HAVEWPA.dat");
    filetmpwifi.open(QFile::ReadOnly);
    QString stmp =filetmpwifi.readAll();
    QString stmp2="wpa_supplicant";
    if(!stmp.contains(stmp2) ){// ru guo mei you qi dong wpa_supplicant cheng xu
        if(havewlanflag) {
            qDebug("have wpa_supplicant start");
            system("wpa_supplicant -B -d -i wlan0 -c /etc/wifi/wpa_supplicant.conf ");
            openwpa();
            qDebug("have wpa_supplicant end");
        }
    }else if(havewlanflag){
        openwpa();
        qDebug("have openwpa");
    }

    DipWifi = new QLineEdit;
    im = new InputMethod;
    wifigetdtipcount=1;
    QLabel *pipLabel1 = new QLabel;
    QLabel *pSonnetLabel= new QLabel;
    QLabel *ppassnetLabel= new QLabel;
    QLabel *pDNS = new QLabel;
    QLabel *Diplabel = new QLabel;
    QLabel *pname = new QLabel;
    QLabel *pkey = new QLabel;
    QLabel *pLinkStateLab = new QLabel;
    QLabel *pkeytype = new QLabel;
    timerwifi66= new QTimer;
    connect(timerwifi66,SIGNAL(timeout()),this,SLOT(slotZTimeGetDTIp()));
       m_pTimer = new QTimer(this);
       m_pTimer->setInterval(5000);
       m_pTimer->start();

     connect(m_pTimer, SIGNAL(timeout()), this, SLOT(refreshLabelPos()));

    QPushButton *pSaveButton= new QPushButton;
    QPushButton *DGIPButton;DGIPButton = new QPushButton;
    QPushButton *plinkButton = new QPushButton;
    QPushButton *pscanButton = new QPushButton;
    QPushButton *pforgetButton= new QPushButton(this);
    
    qlineedit_ip = new QLineEdit;
    qlineedit_mask = new QLineEdit;
    qlineedit_gw = new QLineEdit;
    qlineedit_dns = new QLineEdit;
    qlineedit_wifiname = new QLineEdit;
    qlineedit_wifikey = new QLineEdit;
    qlineedit_keytype = new QLineEdit;
    qlineedit_keytype->setText("wpa");
    //Dip = new QLineEdit;
    linkStat = new QLineEdit;
    linkStat->setStyleSheet("background-color:rgb(80,120,89,80);");
    qlineedit_wifikey->installEventFilter(im);
    qlineedit_wifikey->setObjectName("qlineedit_wifikey");
    qlineedit_wifiname->installEventFilter(im);
    qlineedit_wifiname->setObjectName("qlineedit_wifiname");
    qlineedit_ip->installEventFilter(im);
    qlineedit_ip->setObjectName("qlineedit_ip");
    qlineedit_mask->installEventFilter(im);
    qlineedit_mask->setObjectName("qlineedit_mask");
    qlineedit_gw->installEventFilter(im);
    qlineedit_gw->setObjectName("qlineedit_gw");
    qlineedit_dns->installEventFilter(im);
    qlineedit_dns->setObjectName("qlineedit_dns");
    qlineedit_keytype->installEventFilter(im);
    qlineedit_keytype->setObjectName("qlineedit_keytype");

    connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));//connect the input method

    listWidget = new QListWidget(this);
    listWidget->setWordWrap(true);
    listWidget->setAutoScroll(true);
    listWidget->setResizeMode(QListView::Adjust);
    listWidget->setMovement(QListView::Static);

    if(g_lcdsize == LCDSIZE_1280x800) {
        listWidget->setIconSize(QSize(74,74));
    }
    else if(g_lcdsize == LCDSIZE_1024x768)
	{
		listWidget->setIconSize(QSize(70,70));

	}else if(g_lcdsize == LCDSIZE_800x600)
	{
		listWidget->setIconSize(QSize(60,60));
	}else  if(g_lcdsize == LCDSIZE_800x480)
	{
		listWidget->setIconSize(QSize(60,60));
	}else if(g_lcdsize == LCDSIZE_480x272)
	{
		listWidget->setIconSize(QSize(25,25));
	}


    connect(listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(chosewifi()));
	 if(g_lcdsize == LCDSIZE_480x272)
	 {
		 pLinkStateLab->setText(tr("当前:"));
		 pipLabel1->setText(tr("静态IP地址:"));
		 pSonnetLabel->setText(tr("子网掩码:"));
		 ppassnetLabel->setText(tr("网关:"));
		 pDNS->setText(tr("DNS:"));
		 Diplabel->setText(tr("动态IP:"));
	 
		 pname->setText(tr("其他WIFI:"));
		 pkey->setText(tr("密码:"));
		 pkeytype->setText(tr("加密方式:"));
	
		 pSaveButton->setText(tr(" 保存 "));
		 DGIPButton->setText(tr(" 获取动态IP "));
		 plinkButton->setText(tr(" 连接 "));
		 pscanButton->setText(tr(" 刷新 "));
		 pforgetButton->setText(tr(" 忘记所有 "));
	
	 }else{
		 pLinkStateLab->setText(tr("当前连接 :"));
		 pipLabel1->setText(tr("静态IP地 址："));
		 pSonnetLabel->setText(tr("子网掩码："));
		 ppassnetLabel->setText(tr("默认网关："));
		 pDNS->setText(tr("DNS 地址："));
		 Diplabel->setText(tr("动态IP："));
		// pname->setText(tr("WIFI名字："));
		// pname->setText(tr("隐藏WIFI名字："));
		 pname->setText(tr("其他WIFI："));
		 pkey->setText(tr("密码："));
		 pkeytype->setText(tr("加密方式："));
	
		 pSaveButton->setText(tr("保存静态IP"));
		 DGIPButton->setText(tr("获取动态IP"));
		 plinkButton->setText(tr("	连接	"));
		 pscanButton->setText(tr("刷新网络"));
		 pforgetButton->setText(tr("忘记所有密码"));
	}


    qlineedit_ip->setText(tr("192.168.1.17"));
    qlineedit_mask->setText(tr("255.255.255.0"));
    qlineedit_dns->setText(tr("223.5.5.5"));

    QFile file1("/etc/init.d/wifi_sh");
    file1.open(QFile::ReadOnly);
    QString setpath=file1.readAll();
    file1.close();
    QString iptmp,masktmp,gwtmp,dnstm;
    int beganip=0;
    int beganmaskp=0;
    int begangw=0;
    int begandns=0;
    int notset=0;

    int onceip=1;
    int oncemask=1;
    int oncetmo=1;
    for(int i=0;i<setpath.length();i++)
    {
        if(setpath[i]=='4' && setpath[i+1]=='4' && setpath[i+2]=='4'){
            notset=1;
        }
        if(setpath[i]=='l' && setpath[i+1]=='a' && setpath[i+2]=='n'&&oncetmo){
         beganip=1;
         i+=5;
         oncetmo=0;
     }
        if(beganip)
        if(setpath[i]=='l' && setpath[i+1]=='a' && setpath[i+2]=='n'){
         beganip=2;
         i+=5;
     }

     if(setpath[i]=='m' && setpath[i+1]=='a' && setpath[i+2]=='s'){
         beganmaskp=1;
         i+=5;
     }

     if(setpath[i]=='g' && setpath[i+1]=='w'){
         begangw=1;
         i+=3;
     }

     if(beganip==2){
         if(setpath[i]!=' ' && onceip)
             iptmp.append(setpath[i]);
         else
             onceip=0;
     }

     if(beganmaskp){
         if(setpath[i]!='r' && oncemask)
             masktmp.append(setpath[i]);
         else
             oncemask=0;
     }

     if(begangw){
             gwtmp.append(setpath[i]);
     }
    }

    QFile file32("/etc/resolv2.conf");
    file32.open(QFile::ReadOnly);
    QString dnsname=file32.readAll();
    for(int i=0;i<dnsname.length();i++)
    {
     if(dnsname[i]=='v' && dnsname[i+1]=='e' && dnsname[i+2]=='r'){
         begandns=1;
         i+=3;
     }
     if(begandns){
             dnstm.append(dnsname[i]);
     }
    }
    if(beganip && beganmaskp &&notset) {// jing tai can shu
       qlineedit_ip          ->setText(iptmp);
       qlineedit_mask->setText(masktmp);
       qlineedit_gw->setText(gwtmp);
       qlineedit_dns->setText(dnstm);
    }

  //  Dip->setText(tr(" "));
    DipWifi->setText(tr(" "));

    pipLabel1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pSonnetLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ppassnetLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pDNS->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    Diplabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pSaveButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    plinkButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pscanButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    DGIPButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pforgetButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pname->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pkey->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pkeytype->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_ip->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_mask->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_gw->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_dns->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    //Dip->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    DipWifi->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_wifiname->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_wifikey->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qlineedit_keytype->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    connect(pSaveButton, SIGNAL(clicked()), this, SLOT(slotSaveData()));
    connect(DGIPButton, SIGNAL(clicked()), this, SLOT(slotDTHIPButton()));
    connect(plinkButton,SIGNAL(clicked()),this,SLOT(wifiLink()));
    connect(pscanButton,SIGNAL(clicked()),this,SLOT(wifiScan()));
    connect(pforgetButton,SIGNAL(clicked()),this,SLOT(forgetPasswd()));
    
    QGridLayout *pSubLayout = new QGridLayout;


		if(g_lcdsize != LCDSIZE_480x272)
		{ 
			pSubLayout->addWidget(pLinkStateLab,		0, 0, 1, 2);
			pSubLayout->addWidget(pipLabel1,			0+1, 0, 1, 2);
			pSubLayout->addWidget(pSonnetLabel, 		1+1, 0, 1, 2);
			pSubLayout->addWidget(ppassnetLabel,		2+1, 0, 1, 2);
			pSubLayout->addWidget(pDNS, 				3+1, 0, 1, 3);
			pSubLayout->addWidget(Diplabel, 			4+1, 0, 1, 2);
			pSubLayout->addWidget(pname,				5+1, 0, 1, 2);
			pSubLayout->addWidget(pkeytype, 			6+1, 0, 1, 2);
			pSubLayout->addWidget(pkey, 				6+1+1, 0, 1, 2);
			pSubLayout->addWidget(pSaveButton,			7+1+1, 1, 1, 1);
			pSubLayout->addWidget(DGIPButton,			7+1+1, 5, 1, 1);
			pSubLayout->addWidget(plinkButton,			7+1+1, 7, 1, 1);
			pSubLayout->addWidget(pscanButton,			7+1+1, 6, 1, 1);
			pSubLayout->addWidget(pforgetButton,		7+1+1, 3, 1, 1);
	
			pSubLayout->addWidget(linkStat, 			0, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_ip, 		0+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_mask,		1+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_gw, 		2+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_dns,		3+1, 2, 1, 2);
			//	pSubLayout->addWidget(Dip,					4+1, 2, 1, 2);
			pSubLayout->addWidget(DipWifi,					4+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_wifiname,	5+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_keytype,	6+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_wifikey,	6+1+1, 2, 1, 2);
			pSubLayout->addWidget(listWidget,			0, 4, 8+1, 8);
		}else{
			pSubLayout->addWidget(pLinkStateLab,		  0, 0, 1, 2);
			pSubLayout->addWidget(pipLabel1,			  1, 0, 1, 2);
			pSubLayout->addWidget(pSonnetLabel, 		  2, 0, 1, 2);
			pSubLayout->addWidget(ppassnetLabel,		  3, 0, 1, 2);
			pSubLayout->addWidget(pDNS, 				  4, 0, 1, 3);
			pSubLayout->addWidget(Diplabel, 			  5, 0, 1, 2);
			pSubLayout->addWidget(pkeytype, 		  6, 0, 1, 2);
			pSubLayout->addWidget(pkey, 			  7, 0, 1, 2);
	
			QHBoxLayout *may_tmp = new QHBoxLayout;
	
			may_tmp->addWidget(pSaveButton);
			may_tmp->addStretch();
			may_tmp->addWidget(pforgetButton);
			may_tmp->addStretch();
			may_tmp->addWidget(DGIPButton);
			may_tmp->addStretch();
			may_tmp->addWidget(pscanButton);
			may_tmp->addStretch();
			may_tmp->addWidget(plinkButton);
	
	
			pSubLayout->addLayout(may_tmp, 8,0,1,12);
		
	
	//		pSubLayout->addWidget(pSaveButton,		  8, 1, 1, 1);
	//		pSubLayout->addWidget(pforgetButton,	  8, 2, 1, 2);
	//		pSubLayout->addWidget(DGIPButton,		  8, 4, 1, 2);
	//		pSubLayout->addWidget(pscanButton,		  8, 6, 1, 1);
	//		pSubLayout->addWidget(plinkButton,		  8, 7, 1, 1);
	
			
			
	
			pSubLayout->addWidget(linkStat, 		  0, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_ip, 	  0+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_mask,	  1+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_gw, 	  2+1, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_dns,		  3+1, 2, 1, 2);
			//	pSubLayout->addWidget(Dip,					  4+1, 2, 1, 2);
			pSubLayout->addWidget(DipWifi,				  4+1, 2, 1, 2);
		
			pSubLayout->addWidget(qlineedit_keytype,	  6, 2, 1, 2);
			pSubLayout->addWidget(qlineedit_wifikey,	  6+1, 2, 1, 2);
			pSubLayout->addWidget(listWidget,		  0, 4, 8, 8);
	
		}
		

    pSubLayout->setMargin(20);
    pSubLayout->setSpacing(10);
    QFrame *pFrame = new QFrame;
    pFrame->setLayout(pSubLayout);

    QGridLayout *pMainLayout = new QGridLayout;
    pMainLayout->addWidget(pFrame, 0, 0, 1, 1);
    pMainLayout->setContentsMargins(40, 15, 40, 15);
    if(havewlanflag)
    {	qDebug("wifi is scan");
        wifiScan();
    }
    pFrame->setObjectName("wifiSettingsFrame");
    this->setJLayout(pMainLayout);
    this->setJTitle(tr("WIFI设置"));

   refreshLabelPos();
   }

}

static int translate_percentage_to_dbm(unsigned int SignalStrengthIndex)
{
	int	SignalPower; // in dBm.

	// Translate to dBm (x=0.5y-95).
	SignalPower = (int)((SignalStrengthIndex + 1) >> 1);
	SignalPower -= 95;

	return SignalPower;
}

void WifiSeting::wifiScan()
{
      if(linkflag){
        openwpa();
        linkflag=0;
      }
      listWidget->clear();
      wificount=0;
        char reply[2048];
        size_t reply_len;
        int index;
        char cmd[20];
        index = 0;
        int whileflag =1;
        if(strcmp(scan(),"OK"))
            ;
        else
            ;
       sleep(1); //fang zhi tai duo wifi shi hai mei sao miao wang jiu xian shi jie guo
       if(strcmp(scan(),"OK"))
           ;
       else
           ;
       usleep(1000);
        while (whileflag) {
            snprintf(cmd, sizeof(cmd), "BSS %d", index++);
            reply_len = sizeof(reply) - 1;
            if(wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), reply, &reply_len, NULL)<0)
                break;
            reply[reply_len] = '\0';

            QString bss(reply);

            if (bss.isEmpty() || bss.startsWith("FAIL")) {
                whileflag =0;
                    break;
                }

            QStringList lines = bss.split(QRegExp("\\n"));

            for (QStringList::Iterator it = lines.begin();it != lines.end(); it++) {
                int pos = (*it).indexOf('=') + 1;
                if (pos < 1)
                    continue;
                if ((*it).startsWith("bssid=")) {
                    bssid = (*it).mid(pos);
                    }
                else if ((*it).startsWith("freq=")) {
                    freq = (*it).mid(pos);
        }
                else if ((*it).startsWith("level=")) {
                    signal = (*it).mid(pos);
        }
                else if ((*it).startsWith("flags=")) {
                    flags = (*it).mid(pos);
        }
                else if ((*it).startsWith("ssid=")) {
                    ssid = (*it).mid(pos);
               }
            }
            if (bssid.isEmpty())
                break;
            QString tmpwpa = "WPA-";
            QString tmpwpa2 = "WPA2-";
            QString tmpwep = "WEP";
            QString tmpess = "ESS";
            int wepflag =0;
            int wpaflag =0;
            int wpaflag2=0;
            int wpaess =0;

            if(flags.contains(tmpess)) {
               wpaess=1;
            }

            if(flags.contains(tmpwpa)) {
               wpaflag=1;
            }
            if(flags.contains(tmpwpa2)) {
                wpaflag2=1;
            }
            if(flags.contains(tmpwep)) {
                wepflag=1;
            }
            if(wpaflag && wpaflag2)
                flagstmp = "WPA/WPA2 ";
            else {
                if(wpaflag)
                    flagstmp="WPA";
                if(wpaflag2)
                    flagstmp="WPA2 ";
            }

            if(wepflag)
                flagstmp="WEP";

            if(wpaess && !wpaflag && !wpaflag2 && !wepflag)
                flagstmp="无密码";

            QString wifiname;
            ssid+="\n";
            wifiname=ssid + flagstmp;

            int signaltmp=signal.toInt();


//			qDebug() << "wifi" << wifiname << "signal" << signaltmp;
            
			if(signaltmp>=0 && signaltmp<=100)
				signaltmp = translate_percentage_to_dbm(signaltmp);
            else if (signaltmp > 0)
                signaltmp = 0 - (256 - signaltmp);	

             
			
            if (signaltmp < minimum)
                signaltmp = minimum;
            else if (signaltmp > maximum)
                signaltmp = maximum;
            if(signaltmp >= -95 && signaltmp < -80)
               listWidget->insertItem(wificount,new QListWidgetItem(QIcon(":/image/linuxdesktop/settingsicon/wifisignal1.png"),wifiname,listWidget));
            if(signaltmp >= -80 && signaltmp < -65)
               listWidget->insertItem(wificount,new QListWidgetItem(QIcon(":/image/linuxdesktop/settingsicon/wifisignal2.png"),wifiname,listWidget));
            if(signaltmp >= -65 && signaltmp < -50)
               listWidget->insertItem(wificount,new QListWidgetItem(QIcon(":/image/linuxdesktop/settingsicon/wifisignal3.png"),wifiname,listWidget));
            if(signaltmp >= -50 && signaltmp < -35)
               listWidget->insertItem(wificount,new QListWidgetItem(QIcon(":/image/linuxdesktop/settingsicon/wifisignal4.png"),wifiname,listWidget));
        }

  }

  void WifiSeting::createImConnect(QString ObjName)
  {
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_ip,SLOT(setText(QString)));
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_mask,SLOT(setText(QString)));
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_gw,SLOT(setText(QString)));
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_dns,SLOT(setText(QString)));
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_wifiname,SLOT(setText(QString)));
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_wifikey,SLOT(setText(QString)));
      disconnect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_keytype,SLOT(setText(QString)));

      if(ObjName=="qlineedit_ip")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_ip,SLOT(setText(QString)));
      if(ObjName=="qlineedit_mask")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_mask,SLOT(setText(QString)));
      if(ObjName=="qlineedit_gw")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_gw,SLOT(setText(QString)));
      if(ObjName=="qlineedit_dns")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_dns,SLOT(setText(QString)));
      if(ObjName=="qlineedit_wifiname")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_wifiname,SLOT(setText(QString)));
      if(ObjName=="qlineedit_wifikey")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_wifikey,SLOT(setText(QString)));
      if(ObjName=="qlineedit_keytype")
          connect(im->keyboard,SIGNAL(setvalue(QString)),qlineedit_keytype,SLOT(setText(QString)));
  }

  void WifiSeting::chosewifi()
  {
      QListWidgetItem*tmp=listWidget->currentItem();
      nowZItemWifiName= tmp->text();
      QFile file1("/etc/wifi/wpa_supplicant.conf");
      file1.open(QFile::ReadWrite);
      QString recover =file1.readAll();
      QString stmp2;
      QString gatetmp;
      QString gatehave;
      QString gateStr="ssid=\"";
      file1.close();
      nowhavewifi=0;
      int i =0;
      int truei=0;
      int wifi_i=0;
      while(nowZItemWifiName[i]!='\n')
      {
          stmp2.append(nowZItemWifiName[i++]);
      }

      if(recover.contains(stmp2)){
        if(havewlanflag){
            QFile file11("/etc/wifi/wpa_supplicant.conf");
            file11.open(QFile::ReadOnly);
         // //  qDebug("start");
          //  qDebug()<<stmp2;
         //   qDebug("end");

            while(!file11.atEnd()) {
                //retmp.append(f.readLine());
                gatetmp=file11.readLine();
                if(gatetmp.contains(gateStr)) {
                   // qDebug()<<gatetmp;
                 //   gatehave.append(gatetmp);// bao cun suo you ssid hang
                    wifi_i++;
                    if(gatetmp.contains(stmp2)) {
                       // qDebug("find ");
                        truei=wifi_i-1;
                    }
                    gatetmp.clear();
                }
            }
            file11.close();

//qDebug("wifi_i=%d",wifi_i);
//qDebug("truei=%d",truei);
          nowhavewifi=1;
          char reply[2048];
          size_t reply_len = sizeof(reply);
          char *cmd1;
          QString command_full1;
          command_full1.append("SELECT_NETWORK ");
          command_full1.append(QString::number(truei));
          qDebug()<<command_full1;
          cmd1 = (command_full1.toAscii()).data();
          wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);

          system("killall -9 udhcpc");
          QFile filetmptt("/etc/init.d/wifi_sh");
          filetmptt.open(QFile::WriteOnly);
          QTextStream stmptt(&filetmptt);
          stmptt<<"#!/bin/sh"<<"\n";
          stmptt<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R "<<"\n";;
          filetmptt.close();
          system("sync");
          system("chmod +x /etc/init.d/wifi_sh");
          QProcess *proc =new QProcess;
          proc->start("/etc/init.d/wifi_sh");// fei zu sai
          usleep(20000);
          filetmptt.open(QFile::WriteOnly);
          QTextStream stmptt2(&filetmptt);
          stmptt2<<"#!/bin/sh"<<"\n";
          stmptt2<<"wpa_supplicant -B -d -i wlan0 -c /etc/wifi/wpa_supplicant.conf "<<"\n";
          stmptt2<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R "<<"\n";
          filetmptt.close();
          system("sync");

          if(havewlanflag) {
              Wifilian wifiliantmp1;
              wifiliantmp1.exec();
          }
        }

      }else {
         Wifipassword linkonewifi;
         linkonewifi.qsignallevelQSlider->setValue((10-signallevel[listWidget->currentRow()]));
         linkonewifi.exec();

             
      }

      char gateway[32] = { 0 };  
	  if(GetIPV4Gateway("wlan0", gateway, 32) == true)
	  {
	
	 	qDebug("gateway: %s", gateway);
	 	qlineedit_gw->setText(QString(gateway));
	 }
  }
  void WifiSeting::wifiLink()
  {
      char reply[2048];
      char replytmp [2];
      size_t reply_len = sizeof(reply);
      size_t reply_lentmp = sizeof(replytmp);
      int righttype=0;
      char *cmd;
      char *cmd1;
      char *cmd2;
      char *cmd3;
      char *cmd4;
      char *cmd5;
      char *cmd6;
      char *cmd7;
      QString keywpa="WPA";
      QString keywep="WEP";
      QString keywpal="wpa";
      QString keywepl="wep";
      QString command_full1;
      QString command_full2;
      QString command_full3;
      QString command_full4;
      QString command_full5;
      QString command_full6;
      QString command_full7;
      if(qlineedit_wifiname->text().isEmpty())
          ;
       else if( (qlineedit_wifikey->text().length()>=8) || (qlineedit_wifikey->text().isEmpty())) {

                  if(qlineedit_wifikey->text().isEmpty())
                 {
                     cmd="ADD_NETWORK";
                     wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), replytmp, &reply_lentmp, NULL);

                     cmd5="DISABLE_NETWORK all";
                     wpa_ctrl_request(ctrl_conn, cmd5, strlen(cmd5), reply, &reply_len, NULL);


                     command_full1.append("SET_NETWORK ");
                     command_full1.append(replytmp[0]);
                     command_full1.append(" ssid ");
                     command_full1.append("\"");
                     command_full1.append(qlineedit_wifiname->text());
                     command_full1.append("\"");
                     cmd1 = (command_full1.toAscii()).data();
                     wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);


                   //  cmd="SET_NETWORK 6 PSK \"crl6crl6crl6\"";
                     command_full2.append("SET_NETWORK ");
                     command_full2.append(replytmp[0]);
                     command_full2.append(" key_mgmt NONE");
                  //   command_full2.append(qlineedit_password->text().toAscii().data());
                     cmd2 = (command_full2.toAscii()).data();
                     wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);

                  //   cmd="SELECT_NETWORK 6";
                     command_full3.append("SELECT_NETWORK ");
                     command_full3.append(replytmp[0]);
                     cmd3 = (command_full3.toAscii()).data();
                     //"select_network cmd= %s",cmd3);
                     wpa_ctrl_request(ctrl_conn, cmd3, strlen(cmd3), reply, &reply_len, NULL);

                  //   cmd="ENABLE_NETWORK 6";
                     command_full4.append("ENABLE_NETWORK ");
                     command_full4.append(replytmp[0]);
                     cmd4 = (command_full4.toAscii()).data();
                     wpa_ctrl_request(ctrl_conn, cmd4, strlen(cmd4), reply, &reply_len, NULL);
                    righttype=1;
                 }else{
                 if((qlineedit_keytype->text().contains(keywpa))
                         || (qlineedit_keytype->text().contains(keywpal))){
                     qDebug("link wpa wifi");
                     cmd="ADD_NETWORK";
                     wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), replytmp, &reply_lentmp, NULL);

                     command_full5.append("DISABLE_NETWORK ");
                     command_full5.append((replytmp[0]-1));
                     cmd5 = (command_full5.toAscii()).data();
                     cmd5="DISABLE_NETWORK all";
                     wpa_ctrl_request(ctrl_conn, cmd5, strlen(cmd5), reply, &reply_len, NULL);


                     command_full1.append("SET_NETWORK ");
                     command_full1.append(replytmp[0]);
                     command_full1.append(" ssid ");
                    // command_full1.append("\"123456789bbb\"");
                     command_full1.append("\"");
                     command_full1.append(qlineedit_wifiname->text());
                     command_full1.append("\"");
                    // cmd="SET_NETWORK 4 ssid \"crl67crl678\"";
                     cmd1 = (command_full1.toAscii()).data();
                     //"set_network ssid cmd= %s",cmd1);
                     wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);
                     //"set_network 0 ssid= %s",reply);

                   //  cmd="SET_NETWORK 6 PSK \"crl6crl6crl6\"";
                     command_full2.append("SET_NETWORK ");
                     command_full2.append(replytmp[0]);
                     command_full2.append(" psk ");
                     command_full2.append("\"");
                   //  command_full2.append("\"crl6crl6crl6\"");
                     command_full2.append(qlineedit_wifikey->text().toAscii().data());
                     command_full2.append("\"");
                  //   command_full2.append(qlineedit_password->text().toAscii().data());
                     cmd2 = (command_full2.toAscii()).data();
                     //"set_network psk cmd= %s",cmd2);
                     wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);
                     //"set_network 0 psk= %s",reply);

                  //   cmd="SELECT_NETWORK 6";
                     command_full3.append("SELECT_NETWORK ");
                     command_full3.append(replytmp[0]);
                     cmd3 = (command_full3.toAscii()).data();
                     wpa_ctrl_request(ctrl_conn, cmd3, strlen(cmd3), reply, &reply_len, NULL);

                     command_full4.append("ENABLE_NETWORK ");
                     command_full4.append(replytmp[0]);
                     cmd4 = (command_full4.toAscii()).data();
                     wpa_ctrl_request(ctrl_conn, cmd4, strlen(cmd4), reply, &reply_len, NULL);
                     righttype=1;
                 }else{
                     //wep
                     if( (qlineedit_keytype->text().contains(keywep)) ||(qlineedit_keytype->text().contains(keywepl)))
                         {
                         cmd="ADD_NETWORK";
                         wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), replytmp, &reply_lentmp, NULL);

                         command_full5.append("DISABLE_NETWORK ");
                         command_full5.append((replytmp[0]-1));
                         cmd5 = (command_full5.toAscii()).data();
                         cmd5="DISABLE_NETWORK all";
                         wpa_ctrl_request(ctrl_conn, cmd5, strlen(cmd5), reply, &reply_len, NULL);

                         command_full1.append("SET_NETWORK ");
                         command_full1.append(replytmp[0]);
                         command_full1.append(" ssid ");
                         command_full1.append("\"");
                         command_full1.append(qlineedit_wifiname->text());
                         command_full1.append("\"");
                         cmd1 = (command_full1.toAscii()).data();
                         wpa_ctrl_request(ctrl_conn, cmd1, strlen(cmd1), reply, &reply_len, NULL);

                         command_full6.append("SET_NETWORK ");
                         command_full6.append(replytmp[0]);
                         command_full6.append(" key_mgmt NONE");
                         cmd6 = (command_full6.toAscii()).data();
                         wpa_ctrl_request(ctrl_conn, cmd6, strlen(cmd6), reply, &reply_len, NULL);

                         command_full7.append("SET_NETWORK ");
                         command_full7.append(replytmp[0]);
                         command_full7.append(" wep_key0 ");
                         command_full7.append("\"");
                         command_full7.append(qlineedit_wifikey->text().toAscii().data());
                         command_full7.append("\"");
                         cmd7 = (command_full7.toAscii()).data();
                         wpa_ctrl_request(ctrl_conn, cmd7, strlen(cmd7), reply, &reply_len, NULL);

                         command_full2.append("SET_NETWORK ");
                         command_full2.append(replytmp[0]);
                         command_full2.append(" wep_tx_keyidx 0");
                         cmd2 = (command_full2.toAscii()).data();
                         wpa_ctrl_request(ctrl_conn, cmd2, strlen(cmd2), reply, &reply_len, NULL);

                         command_full3.append("SELECT_NETWORK ");
                         command_full3.append(replytmp[0]);
                         cmd3 = (command_full3.toAscii()).data();
                         wpa_ctrl_request(ctrl_conn, cmd3, strlen(cmd3), reply, &reply_len, NULL);
                         command_full4.append("ENABLE_NETWORK ");
                         command_full4.append(replytmp[0]);
                         cmd4 = (command_full4.toAscii()).data();
                         wpa_ctrl_request(ctrl_conn, cmd4, strlen(cmd4), reply, &reply_len, NULL);
                         righttype=1;
                     } else{
                         QDialog * setdialog = new QDialog;
                         QLabel * settmp = new QLabel;
                         settmp->setText(tr("加密方式不合法"));
                         settmp->setStyleSheet("color:red;");
                         QTimer*timer = new QTimer(setdialog);
                         timer->start(600);
                         connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
                         QGridLayout *tmplayout = new QGridLayout;
                         tmplayout->addWidget(settmp,0,0,1,1);
                         setdialog->setLayout(tmplayout);
                         setdialog->setWindowFlags(Qt::FramelessWindowHint);
                         setdialog->exec();
                         righttype=0;
                     }
                 }
            }
                  if(righttype) {
                  system("killall -9 udhcpc");
                  QFile filetmptt("/etc/init.d/wifi_sh");
                  filetmptt.open(QFile::WriteOnly);
                  QTextStream stmptt(&filetmptt);
                  stmptt<<"#!/bin/sh"<<"\n";
                  stmptt<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R "<<"\n";;
                  filetmptt.close();
                  system("sync");
                  system("chmod +x /etc/init.d/wifi_sh");
                  QProcess *proc =new QProcess;
                  proc->start("/etc/init.d/wifi_sh");// fei zu sai
                  usleep(20000);
                  filetmptt.open(QFile::WriteOnly);
                  QTextStream stmptt2(&filetmptt);
                  stmptt2<<"#!/bin/sh"<<"\n";
                  stmptt2<<"wpa_supplicant -B -d -i wlan0 -c /etc/wifi/wpa_supplicant.conf "<<"\n";;
                  stmptt2<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R "<<"\n";
                  filetmptt.close();
                  system("sync");

                  QFile file1("/etc/wifi/wpa_supplicant.conf");
                  file1.open(QFile::ReadWrite);
                  QString recover =file1.readAll();
                  file1.close();
                  nowhavewifi=0;
                  if(recover.contains(qlineedit_wifiname->text()))//{
                      nowhavewifi=1;

                  if(havewlanflag) {
                      usleep(100);
                      Wifilian wifiliantmp1;
                      wifiliantmp1.exec();
                  }
                }

      }else {
          if( (qlineedit_wifikey->text().length()>=1) && (qlineedit_wifikey->text().length()<8)) {
          QDialog * setdialog = new QDialog;
          QLabel * settmp = new QLabel;
          settmp->setText(tr("有密码时,密码长度必须大于等于8位!"));
          settmp->setStyleSheet("color:red;");
          QTimer*timer = new QTimer(setdialog);
          timer->start(600);
          connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
          QGridLayout *tmplayout = new QGridLayout;
          tmplayout->addWidget(settmp,0,0,1,1);
          setdialog->setLayout(tmplayout);
          setdialog->setWindowFlags(Qt::FramelessWindowHint);
          setdialog->exec();
       }
    }
            system("sync");
  }


  void WifiSeting::slotSaveData()
  {
      int flag=0;
      int zifuipflag=0;
      QString tmpp=qlineedit_ip->text();
      flag=IsIPaddress(tmpp);
      tmpp=qlineedit_mask->text();
      flag=IsIPaddress(tmpp);
      tmpp=qlineedit_gw->text();
      flag=IsIPaddress(tmpp);
      tmpp=qlineedit_dns->text();
      flag=IsIPaddress(tmpp);

      QRegExp rx("[._0-9_\n_ ]+");
      if( (rx.exactMatch(qlineedit_ip->text())) && (rx.exactMatch(qlineedit_mask->text())) &&(rx.exactMatch(qlineedit_gw->text())) &&(rx.exactMatch(qlineedit_dns->text())))
          zifuipflag=1;
      if((flag) && (zifuipflag)) {
      linkStat->setEnabled(false);
      m_pTimer->stop();
       QFile::remove("/etc/init.d/wifi_sh");
      QFile file1("/etc/init.d/wifi_sh");
      file1.open(QFile::WriteOnly);
      QTextStream s(&file1);
      s<<"#!/bin/sh"<<"\n";
      s<<"ifconfig wlan0 ";
      s<<qlineedit_ip->text();
      s<<" netmask ";
      s<<qlineedit_mask->text()<<"\n";
      s<<"route add default gw ";
      s<<qlineedit_gw->text()<<"\n";
      file1.close();
      system("chmod +x /etc/init.d/wifi_sh");
      system("/etc/init.d/wifi_sh"); // li ji sheng xiao

      file1.open(QFile::WriteOnly);
      s<<"#!/bin/sh"<<"\n";
      s<<"#44444"<<"\n";
      s<<"wpa_supplicant -B -d -i wlan0 -c /etc/wifi/wpa_supplicant.conf "<<"\n";
      s<<"ifconfig wlan0 ";
      s<<qlineedit_ip->text();
      s<<" netmask ";
      s<<qlineedit_mask->text()<<"\n";
      s<<"route add default gw ";
      s<<qlineedit_gw->text()<<"\n";
      file1.close();
      system("chmod +x /etc/init.d/wifi_sh");

      QFile file2("/etc/resolv.conf");
      file2.open(QFile::WriteOnly);
      QTextStream s2(&file2);
      s2<<"nameserver ";
      s2<<qlineedit_dns->text()<<"\n";
      file2.close();
      //Dip->setText("");
      DipWifi->setText("");

      QFile file3("/etc/resolv2.conf");
      file3.open(QFile::WriteOnly);
      QTextStream s3(&file3);
      s3<<"nameserver ";
      s3<<qlineedit_dns->text()<<"\n";
      file3.close();
      m_pTimer->start();
      linkStat->setEnabled(true);
      system("sync");
     }else {
          QDialog * setdialog = new QDialog;
          QLabel * settmp = new QLabel;
          settmp->setText(tr("参数不合法"));
          settmp->setStyleSheet("color:red;");
          QTimer*timer = new QTimer(setdialog);
          timer->start(800);
          connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
          QGridLayout *tmplayout = new QGridLayout;
          tmplayout->addWidget(settmp,0,0,1,1);
          setdialog->setLayout(tmplayout);
          setdialog->setWindowFlags(Qt::FramelessWindowHint);
          setdialog->exec();
     }
  }

  WifiSeting::~WifiSeting()
  {
   //   system("sync");
      qDebug("exit");
  }
void  WifiSeting::slotZTimeGetDTIp()
{
    if(wifigetdtipcount) {
        linkStat->setEnabled(false);
        m_pTimer->stop();
    system("ifconfig wlan0 > /tmp/islinkokwifi6.c");
    QFile filetmplink("/tmp/islinkokwifi6.c");
    filetmplink.open(QFile::ReadOnly);
    QString stmp =filetmplink.readAll();
    QString stmp2="Mask:";
    QString stmp3="Bcast:";

    system("iwconfig wlan0 > /tmp/islinkokwlan6.c");
    QFile filetmplink3("/tmp/islinkokwlan6.c");
    filetmplink3.open(QFile::ReadOnly);
    QString stmp33 =filetmplink3.readAll();
    //)<<stmp33;
    QString stmp23="ESSID:off/any";

    if(stmp.contains(stmp2) && stmp.contains(stmp3) && (!stmp33.contains(stmp23)))
    {
      system("killall -9 udhcpc");
      int began=0;
      int ON =1;
      system("ifconfig wlan0 | grep \"inet addr:\" > /tmp/wifiip.c");//inet addr:192.168.23.2  Bcast:192.168.23.255  Mask:255.255.255.0
      QFile filewifi("/tmp/wifiip.c");
      filewifi.open(QIODevice::ReadWrite);
      QString str(filewifi.readAll());
      QString tmp;
      for(int i = 0;i<str.length();i++)
      {
          if(str[i]==':'){
              i++;
              began=1;
          }
          if(began)
          if(str[i]!=' '&& (ON) && str[i]!='B')
             tmp.append(str[i]);
          if(str[i]=='B')
              ON=0;
      }
     //  Dip ->setText(tmp);
       DipWifi->setText(tmp);
       wifigetdtipcount=0;
       timerwifi66->stop();
    }
   if(wifigetdtipcount>20) {
           //"fale444");
           QDialog * setdialog = new QDialog;
           QLabel * settmp = new QLabel;
           settmp->setText(tr("请检查WIFI连接"));
           settmp->setStyleSheet("color:red;");
           QTimer*timer = new QTimer(setdialog);
           timer->start(1000);
           connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
           QGridLayout *tmplayout = new QGridLayout;
           tmplayout->addWidget(settmp,0,0,1,1);
           setdialog->setLayout(tmplayout);
           setdialog->setWindowFlags(Qt::FramelessWindowHint);
           setdialog->exec();
           wifigetdtipcount=0;
           timerwifi66->stop();
   }
m_pTimer->start();
linkStat->setEnabled(true);
    }

}
  void WifiSeting::slotDTHIPButton()
  {

          //Dip ->setText(" ");
          DipWifi->setText(" ");
          system("killall -9 udhcpc &");
          QFile file6("/etc/init.d/wifi_sh");
          file6.open(QFile::WriteOnly);
          QTextStream s6(&file6);
          s6<<"#!/bin/sh"<<"\n";
          s6<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R"<<"\n";
          file6.close();
          system("sync");
          system("chmod +x /etc/init.d/wifi_sh");
          QProcess *proc =new QProcess;
          proc->start("/etc/init.d/wifi_sh");// fei zu sai
          wifigetdtipcount=1;
          timerwifi66->start(1000);

          file6.open(QFile::WriteOnly);
          QTextStream s66(&file6);
          s66<<"#!/bin/sh"<<"\n";
          s66<<"wpa_supplicant -B -d -i wlan0 -c /etc/wifi/wpa_supplicant.conf "<<"\n";
          s66<<"udhcpc -b -i wlan0 -p /var/run/udhcpd.pid -R"<<"\n";
          file6.close();
          system("chmod +x /etc/init.d/wifi_sh");
          system("sync");
  }

  void WifiSeting::scanRequest()
  {
      char reply[2048];
      size_t reply_len;
      int index;
      char cmd[20];
      index = 0;
      int whileflag =1;

      if(strcmp(scan(),"OK"))
          ;
      else
          ;

      while (whileflag) {
          snprintf(cmd, sizeof(cmd), "BSS %d", index++);
          reply_len = sizeof(reply) - 1;
          if(wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), reply, &reply_len, NULL)<0)
              break;
          reply[reply_len] = '\0';

          QString bss(reply);

          if (bss.isEmpty() || bss.startsWith("FAIL")) {
              whileflag =0;
                    for(int i=0;i<10000;i++)
                        ;
                  break;
              }

          QStringList lines = bss.split(QRegExp("\\n"));

          for (QStringList::Iterator it = lines.begin();it != lines.end(); it++) {
              int pos = (*it).indexOf('=') + 1;
              if (pos < 1)
                  continue;

              if ((*it).startsWith("bssid=")) {
                  bssid = (*it).mid(pos);
                  }
              else if ((*it).startsWith("freq=")) {
                  freq = (*it).mid(pos);
      }
              else if ((*it).startsWith("level=")) {
                  signal = (*it).mid(pos);
      }
              else if ((*it).startsWith("flags=")) {
                  flags = (*it).mid(pos);
      }
              else if ((*it).startsWith("ssid=")) {
                  ssid = (*it).mid(pos);
      }
          }
          if (bssid.isEmpty())
              break;
  }

  }

  char * WifiSeting::scan()
  {
      char buf[256];
      size_t len;
      char reply[2048];
      size_t reply_len = sizeof(reply);
      char *cmd="SCAN";
      wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), reply, &reply_len, NULL);
      return reply;
  }

  void WifiSeting::receiveMsgs()
  {
      char buf[256];
      size_t len;

      while (monitor_conn && wpa_ctrl_pending(monitor_conn) > 0) {
          len = sizeof(buf) - 1;
          if (wpa_ctrl_recv(monitor_conn, buf, &len) == 0) {
              buf[len] = '\0';
          }
      }
  }

  void WifiSeting::openwpa()
  {
      size_t len;
      char buf[2048];
      ctrl_conn = wpa_ctrl_open("/var/run/wpa_supplicant/wlan0");
      monitor_conn = wpa_ctrl_open("/var/run/wpa_supplicant/wlan0");
      if (wpa_ctrl_attach(monitor_conn)) {
          wpa_ctrl_close(monitor_conn);
          monitor_conn = NULL;
          wpa_ctrl_close(ctrl_conn);
          ctrl_conn = NULL;
      }
  }

